// 源插件
import React, { Fragment, PureComponent } from 'react';
import { DateDiff, DateStamp, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
// 视图插件
import { Button, Card, Divider, Form, message, Modal, notification } from 'antd';
// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTablePro from '@/components/UpgradeStandardTable/StandardTablePro';
import { connect } from 'dva';
import AddCitiStock from './AddCitiStock';

// css OR less预编译器

// 图片

/**
 *  Describe:数据连接
 */

@connect(({ cpb, loading }) => ({
  cpb,
  loading: loading.models.cpbRule,
}))
@Form.create()
class CitiStock extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    dataSource: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourcePreview: {
      data: [],
      total: [],
      code: 0,
    },
    row: {},
    addVisible: false,
    confirmLoading: false,
  };

  dataSourceChange() {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'cpb/GetStockProfit',
      payload: 2,
      callback: res => {
        that.setState({
          dataSource: {
            title: `花旗股票每日盈亏 ${res.list[0].uploadDate.split(' ')[0]}`,
            code: 1,
            data: res.list,
            total: ['profit', 'todayProfit', 'marketValue', 'positionSize'],
            columns: [
              {
                title: '股票代码',
                dataIndex: 'stock',
                type: 'string',
                search: true,
              },
              {
                title: '成本价',
                dataIndex: 'costPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '购买日期',
                dataIndex: 'buyDate',
                type: 'date',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '总收益',
                dataIndex: 'profit',
                type: 'number',
                sorter: true,
              },
              {
                title: '今日收益',
                dataIndex: 'todayProfit',
                type: 'number',
                sorter: true,
              },
              {
                title: '股票数量',
                dataIndex: 'stockNum',
                type: 'number',
                sorter: true,
              },
              {
                title: '现价',
                dataIndex: 'nowPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '市值',
                dataIndex: 'marketValue',
                type: 'number',
                sorter: true,
              },
              {
                title: '操作日志',
                dataIndex: 'mark',
                type: 'string',
              },
            ],
          },
        });
      },
    });
  }

  openAddVisible() {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'cpb/GetStockCpbOperateList',
      callback: res => {
        that.setState({
          addVisible: true,
          dataSourcePreview: {
            title: '今日交易记录',
            code: res.code,
            data: res.list,
            total: [],
            columns: [
              {
                title: '股票代码',
                dataIndex: 'stock',
                type: 'string',
                search: true,
              },
              {
                title: '操作类型',
                dataIndex: 'type',
                type: 'number',
                filters: [
                  // 1sp 2 sc 3 bp 4bc
                  {
                    text: '买入',
                    value: 1,
                  },
                  {
                    text: '卖出',
                    value: 0,
                  },
                ],
                render: (value, row, index) => {
                  return <span>{value === 1 ? '买入' : value === 0 ? '卖出' : null}</span>;
                },
              },
              {
                title: '成交价',
                dataIndex: 'avgPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '操作数量',
                dataIndex: 'stockNumber',
                type: 'number',
                sorter: true,
              },
              {
                title: '操作日期',
                dataIndex: 'settlementDate',
                width: 120,
                type: 'date',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '操作',
                render: (text, record) => {
                  if (record.type === '合计') {
                    return null;
                  }
                  return (
                    <Fragment>
                      <a onClick={() => this.deleteThis(record)}>删除</a>
                    </Fragment>
                  );
                },
              },
            ],
          },
        });
      },
    });
  }

  closeAddVisbile() {
    const that = this;
    this.setState({
      addVisible: false,
    });
  }

  closeOkVisbile() {
    const that = this;
    that.setState({
      confirmLoading: true,
    });
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 800);
    })
      .then(() => {
        that.props.form.validateFields((err, values) => {
          if (!err) {
            const { dispatch } = that.props;
            dispatch({
              type: 'cpb/GetGeneratePosition',
              payload: 2,
              callback: res => {
                that.setState(
                  {
                    addVisible: false,
                    confirmLoading: false,
                  },
                  () => {
                    that.dataSourceChange();
                  }
                );
              },
            });
          }
        });
      })
      .catch(() => console.log('Oops errors!'));
  }

  deleteThis(row) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'cpb/DelStockOperate',
      payload: { id: row.id },
      callback: res => {
        that.openAddVisible();
      },
    });
  }

  render() {
    const { addVisible, confirmLoading, row, dataSource, dataSourcePreview } = this.state;
    return (
      <PageHeaderWrapper>
        <Card>
          <Button onClick={this.openAddVisible.bind(this)}>预览与生成信息</Button>
          <br />
          <br />
          <StandardTablePro dataSource={dataSource} />
          <Modal
            destroyOnClose
            title="预览与生成信息"
            visible={addVisible}
            confirmLoading={confirmLoading}
            width="80%"
            centered
            onOk={this.closeOkVisbile.bind(this)}
            onCancel={this.closeAddVisbile.bind(this)}
          >
            <StandardTablePro dataSource={dataSourcePreview} />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    this.dataSourceChange();
  }

  componentWillUnmount() {}
}

export default CitiStock;
